package org.hzz.caffeine.runner;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.hzz.caffeine.db.UserRepository;
import org.hzz.caffeine.entity.User;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author 胖卡
 * @version 1.0.0
 * @date 2024/7/14
 */
@Slf4j
public class EvictionListenerMain {
    public static void main(String[] args) throws InterruptedException {
        LoadingCache<Integer, User> userLoadingCache = Caffeine.newBuilder()
                .maximumSize(1)
                .evictionListener(new EvictionListener())
                .removalListener(new MyRemovalListener())
                .expireAfterWrite(Duration.ofSeconds(3))
                .build(UserRepository::getById);

        userLoadingCache.get(1);
        userLoadingCache.get(2);
        userLoadingCache.get(3);
        // 马上给他失效
        userLoadingCache.invalidate(2);
        // 等待5秒
        TimeUnit.SECONDS.sleep(5);
        userLoadingCache.get(1);
        log.info("over");
    }


    @Slf4j
    static class EvictionListener implements RemovalListener<Integer, User> {
        @Override
        public void onRemoval(@Nullable Integer key, @Nullable User value, RemovalCause cause) {
            log.info("key = {} value = User{ name = {} } {}", key, value.getName(), cause);
        }
    }

    @Slf4j
    static class MyRemovalListener implements RemovalListener<Integer, User> {
        @Override
        public void onRemoval(@Nullable Integer key, @Nullable User value, RemovalCause cause) {
            log.info("key = {} value = User{ name = {} } {}", key, value.getName(), cause);
        }
    }

}
